package com.jnu.student.myfirstapplication;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jnu.student.myfirstapplication.data.BookItem;
import com.jnu.student.myfirstapplication.data.DataBank;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookListFragment extends Fragment {

    // 全局变量
    private ArrayList<BookItem> mBooksList = new ArrayList<>();
    ActivityResultLauncher<Intent> addBookLauncher;
    ActivityResultLauncher<Intent> renameBookLauncher;
    private BookAdapter adapter_local;

    public BookListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment BookListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookListFragment newInstance(String param1, String param2) {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_book_list, container, false);
        // Inflate the layout for this fragment
        // 6 RecycleView
//        addBookItems();     // 添加需要的book items
        mBooksList = new DataBank().LoadBookItems(requireActivity());
        if(0 == mBooksList.size()) {
            mBooksList.add(new BookItem("信息安全数学基础（第2版）", R.drawable.book_1));
            mBooksList.add(new BookItem("软件项目管理案例教程（第4版）", R.drawable.book_2));
            mBooksList.add(new BookItem("创新工程实践", R.drawable.book_no_name));
        }

        RecyclerView recyclerView = rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireActivity());  //线性的布局管理器
        recyclerView.setLayoutManager(layoutManager);           //为recycleView绑定布局管理器

        BookAdapter adapter = new BookAdapter(mBooksList);      //数据管理的适配器
        registerForContextMenu(recyclerView);                   //注册上下文菜单
        recyclerView.setAdapter(adapter);                       //绑定适配器
        adapter_local = adapter;

        // 添加的数据处理
        addBookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        String name = data.getStringExtra("name"); // 获取返回的数据
                        int imageid = data.getIntExtra("imageId", R.drawable.book_1);

                        mBooksList.add(new BookItem(name, imageid));   // 添加数据
                        new DataBank().SaveBookItems(requireActivity(), mBooksList);
                        adapter.notifyItemInserted(mBooksList.size());  // 适配器重新适配一下新出现的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        // 修改用的还是添加的activity和布局，只是多传回了个position
        renameBookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        int position = data.getIntExtra("position",0);
                        String name = data.getStringExtra("name"); // 获取返回的数据

                        mBooksList.get(position).renameTitle(name);   // 修改数据
                        new DataBank().SaveBookItems(requireActivity(), mBooksList);
                        adapter.notifyItemChanged(position);  // 适配器重新适配一下新改变的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        return rootView;
    }
    public void addBookItems() {
        mBooksList.add(new BookItem("信息安全数学基础（第2版）", R.drawable.book_1));
        mBooksList.add(new BookItem("软件项目管理案例教程（第4版）", R.drawable.book_2));
        mBooksList.add(new BookItem("创新工程实践", R.drawable.book_no_name));
    }

    public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {
        private ArrayList<BookItem> mBooksList;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
            private final ImageView bookImage;
            private final TextView bookName;

            public ViewHolder(View view) {
                super(view);
                bookImage = (ImageView) view.findViewById(R.id.image_view_book_cover);
                bookName = (TextView) view.findViewById(R.id.text_view_book_title);
                view.setLongClickable(true);                    // 长按响应
                view.setOnCreateContextMenuListener(this);      // 创建上下文菜单
            }
            public TextView getBookName() {
                return bookName;
            }

            public ImageView getBookCover() {
                return bookImage;
            }

            // 上下文菜单的样子设定
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");

                menu.add(0, 0, this.getAdapterPosition(), "添加");
                menu.add(0, 1, this.getAdapterPosition(), "删除");
                menu.add(0, 2, this.getAdapterPosition(), "修改");
            }
        }

        public BookAdapter(ArrayList<BookItem> mBooksList) {
            this.mBooksList = mBooksList;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_item_layout, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            BookItem bookItem = mBooksList.get(position);
            holder.getBookCover().setImageResource(bookItem.getCoverResourceId());
            holder.getBookName().setText(bookItem.getTitle());
        }

        @Override
        public int getItemCount() {
            return mBooksList.size();
        }
        // 实现必要的方法
    }


    // 点击菜单后的响应事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // 处理菜单项的点击事件
        switch (item.getItemId()) {
            case 0:
                // 菜单项1的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                Intent intentAdd = new Intent(requireActivity(), BookDetailsActivity.class);   // 从当前activity里创建有关参数二那个类的activity
                BookItem bookItemAdd= mBooksList.get(item.getOrder());
                intentAdd.putExtra("imageId", bookItemAdd.getCoverResourceId());
//                startActivity(intent);      // 切换到新activity
                addBookLauncher.launch(intentAdd);     // 执行新activity并处理返回结果
                break;
            case 1:
                // 菜单项2的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("删除图书"+ item.getOrder());
                builder.setMessage("确定删除这一本书吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mBooksList.remove(item.getOrder());
                        new DataBank().SaveBookItems(requireActivity(), mBooksList);
                        adapter_local.notifyItemRemoved(item.getOrder());
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
                break;
            case 2:
                // 菜单项3的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                Intent intentRename = new Intent(requireActivity(), BookDetailsActivity.class);
                BookItem bookItemRename= mBooksList.get(item.getOrder());
                intentRename.putExtra("name",bookItemRename.getTitle());
                intentRename.putExtra("position",item.getOrder());
                renameBookLauncher.launch(intentRename);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }
}